import { useState } from 'react';
import { Button, TimePicker } from 'antd';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import _ from 'lodash'
import { DayUtil } from '../util/utils'

import './TimeDeltaPicker.css';


const TimeDeltaPicker = ({ placeholder, value, onChange }) => {
    const sign = _.isNil(value) || value >= 0;
    const m = DayUtil.dayjsFromMins(Math.abs(value));

    const [positive, setPositive] = useState(sign);
    const [time, setTime] = useState(m);


    const triggerChange = (positive, time) => {
        console.log('triggerChange');
        if (time) {
            let value = time.hour() * 60 + time.minute();
            if (!positive) {
                value = -value;
            }
            onChange(value);
        }
    };
    const onSignChange = () => {
        console.log('onSignChange')
        setPositive(!positive);
        triggerChange(!positive, time);
    };
    const onTimeChange = (time) => {
        console.log('onTimeChange')
        setTime(time);
        triggerChange(positive, time);
    };

    return (
        <span className='time-delta-picker'>
            <Button className='time-delta-picker-addon'
                type='text'
                icon={positive ? <PlusOutlined /> : <MinusOutlined />}
                onClick={onSignChange} />

            <TimePicker
                format={"HH:mm"}
                showNow={false}
                placeholder={placeholder}
                value={time}
                onChange={onTimeChange}
            />
        </span>
    );
};


export default TimeDeltaPicker